﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Threading;

using Android.App;
using Android.Content.Res;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Net;
using Android.Util;
using Android.Graphics;

using BugSense;
using BugSense.Model;

namespace MWC.NetcampCheckin
{
    [Activity( Label = "Spotkania Netcamp", MainLauncher = true, NoHistory = true)]
    public class NetcampSplash : Activity
    {
        Intent proceed;

        protected override void OnCreate(Bundle bundle)
        {
            try
            {
                base.OnCreate(bundle);

                MWCApp.LogDebug("Netcamp Splash - start");
                Intent service = new Intent(this, typeof(NotificationService));
                this.StartService(service);
                SetContentView(Resource.Layout.NetcampSplash);

                List<TextView> listBold = new List<TextView>();
                listBold.Add(FindViewById<TextView>(Resource.Id.firstParenthasesOfTitle));
                listBold.Add(FindViewById<TextView>(Resource.Id.secondParanthasesOfTitle));
                listBold.Add(FindViewById<TextView>(Resource.Id.boldTextOfSubtitle));
                listBold.Add(FindViewById<TextView>(Resource.Id.boldTextOfTitle));
                setFont("fonts/texgyreheros-regular-webfont.ttf", listBold, TypefaceStyle.Bold);

                List<TextView> listNormal = new List<TextView>();
                listNormal.Add(FindViewById<TextView>(Resource.Id.normalTextOfSubtitle));
                listNormal.Add(FindViewById<TextView>(Resource.Id.normalTextOfTitle));
                setFont("fonts/texgyreheros-regular-webfont.ttf", listNormal, TypefaceStyle.Normal);

                // ImageView i_pizdryczek = FindViewById<ImageView>(Resource.Id.pizdryczek);

                SetPizdryczki();

                new Thread(() =>
                {
                    RunOnUiThread(() =>
                    {
                        
                        ConnectivityManager cm = (ConnectivityManager)GetSystemService(ConnectivityService);

                        if (cm.ActiveNetworkInfo == null || !cm.ActiveNetworkInfo.IsConnectedOrConnecting)
                        {
                            //wyswietl alerta jesli nie ma internetu wiec nie pobralo dat z neta
                            NetcampAlerts.NoInternet(this, true);
                            //ostetecznie konczy aplikacje
                        }
                        else
                        {
                            BugSenseHandler.Instance.InitAndStartSession(new BugSense.Model.ExceptionManager(), ApplicationContext, "w8cc004f");
                            BugSenseHandler.Instance.UnhandledExceptionHandled += (sender, response) =>
                            {
                                string succ = response.HandledSuccessfully ? "successfully." : "unsuccessfully.";
                                Log.Debug("BugSense", "Exception of type " +
                                     response.ExceptionObject.GetType().ToString() +
                                     " handled by BugSense " + succ + "\r\nwith ClientRequest: " +
                                     response.ClientJsonRequest
                                 );
                            };

                            BugSense.Core.Model.LimitedCrashExtraDataList extras = BugSenseHandler.Instance.CrashExtraData;

                            extras.Add(new BugSense.Core.Model.CrashExtraData
                            {
                                Key = "Screen",
                                Value = "NetcampSplash"
                            });

                            bool wasUpdateError = DaysManager.UpdateDays();

                            if (DaysManager.GetLastDay().link == "")
                            {
                                Intent nextMeeting = new Intent(this, typeof(NetcampNextMeeting));
                                Finish();
                                StartActivity(nextMeeting);
                            }
                            else
                            {
                                System.DateTime currentMeeting = DaysManager.GetLastDay().time;
                                MWCApp.LogDebug("DaysManager sie stworzyl");
                                var prefs = GetSharedPreferences("NetcampApp", 0);
                                var prefsEditor = prefs.Edit();

                                int dpi = (int)Resources.DisplayMetrics.DensityDpi;

                                long timestampImageDownloadDevice = prefs.GetLong("TimestampImageDownload", -1);
                                long timestampImageDownloadServer = DaysManager.GetTimeOfLastImage(dpi);
                                if (timestampImageDownloadServer > timestampImageDownloadDevice)
                                {
                                    if (dpi <= Constants.LowDPI)
                                        DaysManager.DownloadImageByteArray(Constants.LowDPI);
                                    else if (dpi <= Constants.MediumDPI)
                                        DaysManager.DownloadImageByteArray(Constants.MediumDPI);
                                    else
                                        DaysManager.DownloadImageByteArray(Constants.HighDPI);

                                    prefsEditor.PutLong("TimestampImageDownload", timestampImageDownloadServer);
                                }

                                long timestampMeeting = prefs.GetLong("TimestampMeeting", 0);
                                int step = prefs.GetInt("CurrentStep", -1);
                                //sprawdz czy obecny dzien spotkania jest rozny od tego trzymanego w aplikacji
                                if (timestampMeeting != DaysManager.ConvertToTimestamp(currentMeeting))
                                {
                                    //zresetuj ustawienia
                                    prefsEditor.PutLong("TimestampMeeting", DaysManager.ConvertToTimestamp(currentMeeting));
                                    prefsEditor.PutInt("CurrentStep", 0);
                                    prefsEditor.PutBoolean("Donation", false);
                                    prefsEditor.PutBoolean("Checked", false);
                                    prefsEditor.PutBoolean("Feedback", false);
                                    prefsEditor.Commit();
                                }

                                //przejdz do odpowiedniej aplikacji w zaleznosci od kroku
                                switch (step)
                                {
                                    // Przy case'ach nie trzeba ponownie aktualizowac wartosci CurrentStep w Preferencjach
                                    case 1:
                                        MWCApp.LogDebug("Wybrales netcamp login");
                                        proceed = new Intent(this, typeof(NetcampLogin));

                                        break;

                                    case 2:
                                        MWCApp.LogDebug("Wybrales NetcampCountTheDistance");
                                        proceed = new Intent(this, typeof(NetcampCountTheDistance));

                                        break;

                                    case 3:
                                        MWCApp.LogDebug("Wybrales NetcampLastStep ");
                                        proceed = new Intent(this, typeof(NetcampLastStep));
                                        break;

                                    default:
                                        proceed = new Intent(this, typeof(NetcampHome));
                                        break;
                                }
                                this.Finish();
                                this.StartActivity(proceed);
                            }
                        }
                    });
                }).Start();


                MWCApp.LogDebug("Netcamp Splash - zakonczenie");
            }
            catch (System.Exception e)
            {
                MWCApp.LogDebug(e);
                NetcampAlerts.UnknownError(this);
            }
        }
        
        public void SetPizdryczki()
        {
            var metrics = Resources.DisplayMetrics;

            for (int i = 0; i < (int)(ConvertPixelsToDp(metrics.WidthPixels) / 46); i++)
            {

                LinearLayout _linearLayout = FindViewById<LinearLayout>(Resource.Id.pf); // zaczep do layoutu, gdzie beda wstawiane zdjecia
                ImageView _imageView = new ImageView(this);
                switch (i)
                {
                    //case 1: _imageView.SetBackgroundResource(Resource.Drawable.pizdryczek1); break;
                    //case 2: _imageView.SetBackgroundResource(Resource.Drawable.pizdryczek2); break;
                    default: _imageView.SetBackgroundResource(Resource.Drawable.multiplikacja); break;
                }

                LinearLayout.LayoutParams _params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent, 0.0f);
                _params.SetMargins(0, 0, 0, 0);
                _linearLayout.AddView(_imageView, _params);
            }

        }

        private float ConvertPixelsToDp(float pixelValue)
        {
            var dp = (float)((pixelValue) / Resources.DisplayMetrics.Density);
            return dp;
        }

        private void setFont(string path, List<TextView> tTV, TypefaceStyle Type)
        {
            AssetManager mgr;
            mgr = Assets;
            Typeface font = Typeface.CreateFromAsset(mgr, path);
            for (int i = 0; i < tTV.Count; i++)
            {
                tTV[i].SetTypeface(font, Type);
            }
        }
    }
}